package com.dchh.android.suverynew.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.presenter.ILoginPresenter;
import com.dchh.android.suverynew.presenter.impl.LoginPresenter;
import com.dchh.android.suverynew.view.ILoginView;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.AutoCompleteTextView.InitAutoCompleteUtil;
import com.dhcc.android.base.common.view.AutoCompleteTextView.MyAutoCompleteTextView;
import com.dhcc.android.base.db.Sqlite.UserDBManager;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.StringUtil;

/**
 * 登录页面
 *
 * @author pengling
 * @date 2014年8月28日
 */
public class LoginActivity extends SBaseActivity implements ILoginView {
    /**
     * top布局用于放置图片
     */
    private LinearLayout top_layout;
    /**
     * top布局放置的图片
     */
    private ImageView title;
    /**
     * 错误提示
     */
    private TextView tip;
    /**
     * 登录表单
     */
    private RelativeLayout labelLogin;
    /**
     * 用户名输入框
     */
    private MyAutoCompleteTextView userName;
    /**
     * 密码输入框
     */
    private MyAutoCompleteTextView password;
    /**
     * 记住密码 复选框
     */
    private CheckBox remenberCheckBox;
    /**
     * 记住密码标签块
     */
    private LinearLayout remenberLabel;
    /**
     * 网络配置标签块
     */
    private LinearLayout netConfigLabel;
    /**
     * 登录按钮
     */
    private Button loginBtn;

    /**
     * 错误提示动画
     */
    private Animation shakeAnimation;
    /**
     * 用户数据库管理类
     */
    private UserDBManager db;
    /**
     * 登陆接口拼接地址
     */
    private String url = "/HttpInterFace/LoginCheck.ashx";
    /**
     * http请求返回结果
     */
    private String result;

    private ILoginPresenter mLoginPresenter = new LoginPresenter(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolBarShow(false);
        SPreferencesManager.initContext(this);
        setContentView(R.layout.main_login);
        //更新app
        mLoginPresenter.updateVersion();
    }

    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    @Override
    protected void setToolBarNavigationIcon(Toolbar toolbar) {

    }

    @Override
    protected void initView() {
        top_layout = (LinearLayout) findViewById(R.id.top_layout);
        title = (ImageView) findViewById(R.id.title);
        tip = (TextView) findViewById(R.id.tip);
        labelLogin = (RelativeLayout) findViewById(R.id.label_login);
        userName = (MyAutoCompleteTextView) findViewById(R.id.username);
        password = (MyAutoCompleteTextView) findViewById(R.id.password);
        remenberCheckBox = (CheckBox) findViewById(R.id.remembercheckbox);
        remenberLabel = (LinearLayout) findViewById(R.id.rememberlabel);
        netConfigLabel = (LinearLayout) findViewById(R.id.netconfig);
        loginBtn = (Button) findViewById(R.id.loginBtn);
        shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.shake);

        // 设置头部图片标签块样式
        LayoutParams layoutParam = new LayoutParams(
                LayoutParams.FILL_PARENT,
                (Constants.screenHight * 2) / 5);
        layoutParam.setMargins(0, 0, 0, 0);
        layoutParam.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        top_layout.setLayoutParams(layoutParam);

        // 设置top图片view样式
        LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
                Constants.screenHight / 6, Constants.screenHight / 6);
        title.setLayoutParams(ll);

        // 设置记住密码和网络配置标签块样式
        LayoutParams layoutParam3 = new LayoutParams(
                LayoutParams.FILL_PARENT,
                Constants.screenHight / 12);
        layoutParam3.setMargins(Constants.screenWidth / 16, 0,
                Constants.screenWidth / 16, 0);
        layoutParam3.addRule(RelativeLayout.BELOW, R.id.ll_user_info);
        RelativeLayout checklabel = (RelativeLayout) this
                .findViewById(R.id.checklabel);
        checklabel.setLayoutParams(layoutParam3);

        // 设置登陆按钮样式
        LayoutParams layoutParam2 = new LayoutParams(
                LayoutParams.FILL_PARENT,
                Constants.screenHight / 12);
        layoutParam2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        loginBtn.setLayoutParams(layoutParam2);

        // 设置表单动画
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.login_anim);
        anim.setFillAfter(true);
        labelLogin.startAnimation(anim);

        // AutoText样式
        CommenUtil.setAutoTextStyle(userName,
                this.getString(R.string.loginActivity_username),
                InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_NEXT,
                R.mipmap.user);
        CommenUtil.setAutoTextStyle(password,
                this.getString(R.string.loginActivity_password),
                InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_PASSWORD,
                EditorInfo.IME_ACTION_GO, R.mipmap.lock);

        // 初始用户登录历史账号
        InitAutoCompleteUtil.initAutoComplete(this,
                MSApplication.LOGIN_HISTORY, userName);

        // 扩大 记住密码 点击范围
        checkClickListener();

        // loginBtn.setHeight(Constants.screenHight/12);

        // 注册监听
        netConfigLabel.setOnClickListener(itemOnClick);
        loginBtn.setOnClickListener(itemOnClick);
        userName.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    password.requestFocus();
                    password.setFocusable(true);
                    return true;
                }
                return false;
            }
        });

        password.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    if (!remenberCheckBox.isChecked()) {// 若没有记住密码，询问
                        isAlertDown(
                                LoginActivity.this,
                                LoginActivity.this
                                        .getString(R.string.loginActivity_alert_isremeber_pwd),
                                0, LoginActivity.this
                                        .getString(R.string.common_sure),
                                LoginActivity.this
                                        .getString(R.string.common_cancel));
                    }
                    return true;
                }
                return false;
            }
        });
        db = new UserDBManager(this);
        tip.setVisibility(View.INVISIBLE);
        tip.setText("");
        db.addDefaultAccount("TEST", "1234567890.");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 双击返回键退出
            if (StringUtil.isFastDoubleClick(500)) {
                return true;
            }

            this.finish();
            overridePendingTransition(android.R.anim.fade_in,
                    android.R.anim.fade_out);
            System.exit(0);
        }
        return true;
    }


    private void isAlertDown(final Context context, String str, final int type,
                             String right, String left) {
        final AlertDialog alertDialog = new AlertDialog(context, str, right,
                left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                alertDialog.dismiss();
                switch (type) {
                    case 0:// 记住密码
                        remenberCheckBox.setChecked(true);
                        break;
                    case 1:// 网络设置
                        Intent intent = new Intent(context, NetConfigActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.push_left_in,
                                R.anim.push_right_out);
                        break;
                    case 2:// 恢复上次任务
                        showProgressDialog("正在载入，请稍后...");
                        userNameValue = SPreferencesManager.getValue(MSApplication.USERNAME, "");
                        passwordValue = SPreferencesManager.getValue(MSApplication.PASSWORD, "");
                        mLoginPresenter.login();
                        break;
                    default:
                        break;
                }

            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
                if (type == 0) {
                    //loginCheck();
                } else if (type == 2) {
                    SPreferencesManager.saveValue(MSApplication.EXCEPTION_FLAG, false);
                }
            }
        });
    }

    String userNameValue;
    String passwordValue;

    /**
     * 跳转到网络设置页面
     */
    private void toNetConfig() {
        if (StringUtil.isFastDoubleClick(500)) {
            return;
        }
        startActivity(new Intent(LoginActivity.this, NetConfigActivity.class));
        overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
    }

    /**
     * checkBox点击范围增大
     */
    private void checkClickListener() {
        String aa = getAccountRememberFlag();
        if (aa.equals("1")) {
            remenberCheckBox.setChecked(true);
            userName.setText(getOldName());
            password.setText(getOldPwd());
            userName.setSelection(getOldName().length());
            password.setSelection(getOldPwd().length());
        } else {
            remenberCheckBox.setChecked(false);
        }

        // 对 布局管理器 注册监听 以达到增加点击范围的作用
        remenberLabel.setOnClickListener(itemOnClick);
    }

    /**
     * 得到是否记住用户密码的flag
     *
     * @return
     */
    public String getAccountRememberFlag() {
        String accountRememberFlag = SPreferencesManager.getValue(MSApplication.ACCOUNT_ISAUTOLOGIN_KEY, "");
        return accountRememberFlag;
    }

    /**
     * 取得保存的用户名
     *
     * @return
     */
    public String getOldName() {
        String username = SPreferencesManager.getValue(MSApplication.ACCOUNT_USERNAME_KEY, "");
        return username;
    }

    /**
     * 取得保存的密码
     *
     * @return
     */
    public String getOldPwd() {
        String password = SPreferencesManager.getValue(MSApplication.ACCOUNT_PASSWORD_KEY, "");
        return password;
    }

    private OnClickListener itemOnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (StringUtil.isFastDoubleClick(500)) {
                return;
            }
            if (v.getId() == R.id.netconfig) {
                toNetConfig();
            } else if (v.getId() == R.id.loginBtn) {
                //mLoginPresenter.login();
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, TaskMainActivity.class);
                startActivity(intent);
                finish();
            } else if (v.getId() == R.id.rememberlabel) {
                remenberCheckBox.setChecked(!remenberCheckBox.isChecked());

            }
        }
    };

    @Override
    public boolean getLastException() {
        // 上次为非正常退出，弹出恢复上次任务的弹框
        boolean ef = SPreferencesManager.getValue(MSApplication.EXCEPTION_FLAG, false);
        return ef;
    }

    @Override
    public void onNeedUpdate() {
        showUpdataDialog();
    }

    @Override
    public void onLastException() {
        isAlertDown(LoginActivity.this, "是否恢复上次任务？", 2, "确定", "取消");
    }

    @Override
    public String getUsername() {
        return userName.getText().toString();
    }

    @Override
    public String getPassword() {
        return password.getText().toString();
    }

    @Override
    public void onLoginUsernameCheck(String msg) {
        tip.setVisibility(View.VISIBLE);
        tip.setText(msg);
        userName.requestFocus();
    }

    @Override
    public void onLoginPasswordCheck(String msg) {
        tip.setVisibility(View.VISIBLE);
        tip.setText(msg);
        password.requestFocus();
    }

    @Override
    public boolean isRemberUsername() {
        return remenberCheckBox.isChecked();
    }

    @Override
    public UserDBManager getDBManager() {
        return db;
    }

    @Override
    public void onLoginSUccess() {
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, TaskMainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void loginErrorNoUser() {
        tip.setText("用户名不存在");
        tip.setVisibility(View.VISIBLE);
    }
}
